from django.shortcuts import render
from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.utils import timezone
from .models import Delivery, DeliveryRoute, DeliveryLog
from .serializers import DeliverySerializer, DeliveryRouteSerializer, DeliveryLogSerializer
from users.permissions import DeliverymanPermission, IsAdmin

# Create your views here.

class DeliveryViewSet(viewsets.ModelViewSet):
    queryset = Delivery.objects.all()
    serializer_class = DeliverySerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_permissions(self):
        if self.action in ['create', 'update', 'partial_update', 'destroy', 'update_status']:
            return [DeliverymanPermission()|IsAdmin()]
        return [permissions.IsAuthenticated()]

    def get_queryset(self):
        user = self.request.user
        if user.role == 'admin':
            return Delivery.objects.all()
        elif user.role == 'deliveryman':
            return Delivery.objects.filter(deliveryman=user)
        return Delivery.objects.none()

    @action(detail=True, methods=['post'])
    def update_status(self, request, pk=None):
        """更新配送状态"""
        delivery = self.get_object()
        new_status = request.data.get('status')
        location = request.data.get('location', '')
        note = request.data.get('note', '')
        
        if new_status not in dict(Delivery.STATUS_CHOICES):
            return Response(
                {'detail': '无效的状态'},
                status=status.HTTP_400_BAD_REQUEST
            )
            
        # 更新状态
        delivery.status = new_status
        if new_status == 'picked':
            delivery.pickup_time = timezone.now()
        elif new_status == 'completed':
            delivery.delivery_time = timezone.now()
        delivery.save()
        
        # 记录日志
        DeliveryLog.objects.create(
            delivery=delivery,
            location=location,
            status=new_status,
            note=note
        )
        
        # 如果配送完成，更新订单状态
        if new_status == 'completed':
            delivery.order.status = 'completed'
            delivery.order.save()
        
        return Response(self.get_serializer(delivery).data)

class DeliveryRouteViewSet(viewsets.ModelViewSet):
    queryset = DeliveryRoute.objects.all()
    serializer_class = DeliveryRouteSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_permissions(self):
        if self.action in ['create', 'update', 'partial_update', 'destroy', 'complete']:
            return [DeliverymanPermission()|IsAdmin()]
        return [permissions.IsAuthenticated()]

    def get_queryset(self):
        user = self.request.user
        if user.role == 'admin':
            return DeliveryRoute.objects.all()
        elif user.role == 'deliveryman':
            return DeliveryRoute.objects.filter(delivery__deliveryman=user)
        return DeliveryRoute.objects.none()

    @action(detail=True, methods=['post'])
    def complete(self, request, pk=None):
        """完成配送路线"""
        route = self.get_object()
        actual_distance = request.data.get('actual_distance')
        actual_time = request.data.get('actual_time')
        
        route.actual_distance = actual_distance
        route.actual_time = actual_time
        route.save()
        
        return Response(self.get_serializer(route).data)

class DeliveryLogViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = DeliveryLog.objects.all()
    serializer_class = DeliveryLogSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        if user.role == 'admin':
            return DeliveryLog.objects.all()
        elif user.role == 'deliveryman':
            return DeliveryLog.objects.filter(delivery__deliveryman=user)
        return DeliveryLog.objects.none()
